/*
 *  Copyright (c) 2014 James Buncle
 * 
 *  Permission is hereby granted, free of charge, to any person obtaining a copy
 *  of this software and associated documentation files (the "Software"), to deal
 *  in the Software without restriction, including without limitation the rights
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *  copies of the Software, and to permit persons to whom the Software is
 *  furnished to do so, subject to the following conditions:
 * 
 *  The above copyright notice and this permission notice shall be included in
 *  all copies or substantial portions of the Software.
 * 
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 *  THE SOFTWARE.
 * 
 */
package com.jbuncle.seleniumiderunner.commands;

import com.jbuncle.seleniumiderunner.TestSuite;
import com.jbuncle.seleniumiderunner.TestDriver;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.script.ScriptException;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;

/**
 *
 * @author James Buncle
 */
public class Basic {

    private final TestDriver driver;

    public Basic(TestDriver driver) {
        this.driver = driver;
    }

    public WebElement findElement(String target) {
        final List<WebElement> elements = findElements(target);
        if (elements.size() < 1) {
            throw new NoSuchElementException("No such element: " + target);
        }
        return elements.get(0);
    }

    public WebElement findElement(By by) {
        return driver.getWebDriver().findElement(by);
    }

    public List<WebElement> findElements(By by) {
        return driver.getWebDriver().findElements(by);
    }

    protected List<WebElement> findElements(String target) {
        final String[] targetParts = target.split("=", 2);
        switch (targetParts[0]) {
            case "id":
                return findElements(By.id(targetParts[1]));
            case "link":
                return findElements(By.linkText(targetParts[1]));
            case "css":
                return findElements(By.cssSelector(targetParts[1]));
            case "name":
                return findElements(By.name(targetParts[1]));
            case "xpath":
                return findElements(By.xpath(targetParts[1]));
            default:
                return findElements(By.xpath(target));
        }

    }

    protected boolean isElementPresent(String target) {
        try {
            driver.getWebDriver().manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
            return findElements(target).size() > 0;
        } finally {
            driver.getWebDriver().manage().timeouts().implicitlyWait(TestSuite.IMPLICITWAITSECONDS, TimeUnit.SECONDS);
        }
    }

    public void type(String target, String value) {
        WebElement element = this.findElement(target);

        if (!element.getAttribute("type").equals("file")) {
            try {
                element.clear();
            } catch (org.openqa.selenium.WebDriverException ex) {
            }
        }
        element.sendKeys(value);
    }

    public void pause(String target) throws InterruptedException {
        Thread.sleep(Long.parseLong(target));
    }

    public void open(String target) {
        try {
            driver.getWebDriver().get(getURL(driver.getBaseURL(), target).toString());
        } catch (MalformedURLException ex) {
            throw new RuntimeException(ex);
        }
    }

    public void store(String target, String value) {
        driver.storeVariable(value, target);
    }

    public void click(String target) {
        this.findElement(target).click();
    }

    public void select(String target, String value) {
        WebElement element = findElement(target);
        String[] valParts = value.split("=", 2);
        switch (valParts[0]) {
            case "label":
                new Select(element).selectByVisibleText("Mr");
                return;
            default:
                throw new UnsupportedOperationException("Unknown select type: " + valParts[0]);
        }
    }

    public void goBack() {
        driver.getWebDriver().navigate().back();
    }

    private URL getURL(URL base, String target) throws MalformedURLException {
        if (target.startsWith("/")) {
            return new URL(base.getProtocol() + "://" + base.getHost() + "/" + target);
        }
        return new URL(base.toString() + "/" + target);
    }

    protected void wait(ExpectedCondition<Boolean> expectation) {
        org.openqa.selenium.support.ui.Wait<WebDriver> wait = new WebDriverWait(driver.getWebDriver(), TestSuite.DEFAULTTIMEOUTSECTONS);
        wait.until(expectation);
    }

    protected String getTitle() {
        return this.driver.getWebDriver().getTitle();
    }

    protected String processJavascript(String script) throws ScriptException {
        return this.driver.processJavascript(script);
    }
}
